import json
import traceback

from 数据类型.position import Position


def load_local_config():
    with open("001.json", mode='rb') as configFile:
        local_config = json.load(configFile)
    return local_config

def peel_position(position_data):
    """
    解析机位数据
    {'machineLocationRelId': 53, 'factoryId': 1, 'proLineId': 1, 'machineLocationId': 22, 'qualitylocationId': 1, 'qualitylocationName': '身袖左前', 'deviceInfoId': 75, 'bindingStatus': 1, 'bindingTime': '2023-08-03', 'deviceType': None, 'deviceNo': '148CCC50C047735AB66D7081F5F4F19F09E820AB', 'proLineCode': None, 'proLineName': None, 'configJson': '{"light":false, "focus":"2.87456748" , "exposure":"3000000", "adjust_delay":"2400", "waist_delay":"2500,1500"}', 'errorPointJsonList': '{"89":"{\\"matrix\\":\\"[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]\\"}","90":"{\\"matrix\\":\\"[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]\\"}","85":"{\\"matrix\\":\\"[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]\\"}"}', 'errorJSONObjectList': None, 'deviceConfig': None}
    """
    positions = []
    try:
        for item in position_data:
            camera_id = item["qualitylocationId"] if "qualitylocationId" in item else ""
            camera_name = item["qualitylocationName"] if "qualitylocationName" in item else ""
            device_no = item["deviceNo"] if "deviceNo" in item else ""
            qualitylocation_id = item["qualitylocationId"] if "qualitylocationId" in item else ""


            capture_region_infos = list()
            if "configJson" in item:
                config_json = item["configJson"]
                regions = json.loads(config_json)
                for region in regions:
                    capture_region = region["captureRegion"]
                    capture_region_id = capture_region["captureRegionId"]
                    capture_region_name = capture_region["captureRegionName"]
                    capture_camera_params = capture_region["config"]

                    defectives = region["defectiveProductss"]
                    defective_infos = list()
                    for defective in defectives:
                        defective_code = defective["defectiveProductsCode"]
                        defective_name = defective["defectiveProductsName"]
                        defective_rel_ids = defective["defectiveProductsDefectiveRelIds"]
                        defective_rel_names = defective["defectiveProductsDefectiveRelNames"]
                        defective_matrix = defective["config"]
                        defective_infos.append(dict(defective_code=defective_code,
                                                    defective_name=defective_name,
                                                    defective_rel_ids=defective_rel_ids,
                                                    defective_rel_names=defective_rel_names,
                                                    defective_matrix=defective_matrix))

                    capture_region_info = dict(capture_region_id=capture_region_id,
                                               capture_region_name=capture_region_name,
                                               capture_camera_params=capture_camera_params,
                                               defective_infos=defective_infos)
                    capture_region_infos.append(capture_region_info)


            p = Position(camera_id, device_no, qualitylocation_id, camera_name, capture_region_infos)
            positions.append(p)
    except Exception as e:
        print(f"----peel_position----error:{e}")
        pass
    return positions


def getPositions():
    config_json = load_local_config()
    positions = peel_position(config_json["qualitylocationList"])
    return positions




def wrapper_flaws(result, camera_id, area_id):
    """ 根据AI质检结果生成FLaw,合格的返回空list """
    """
        {
            "score": 0.45166969299316406,
            "rect": [0,0,0],
            image_url:""
        }
    """
    positions = getPositions()
    is_flaw = any([float(item['score']) >= 1.0 for item in result])
    flaws = []
    if is_flaw is True:
        camera_infos = [position for position in positions if int(position.camera_id) == int(camera_id)]
        if camera_infos and len(camera_infos) > 0:
            camera_info = camera_infos[0]
            capture_region_infos = camera_info.capture_region_infos
            area_infos = [area for area in capture_region_infos if int(area["capture_region_id"]) == int(area_id)]
            if area_infos and len(area_infos) > 0:
                area_info = area_infos[0]
                defective_infos = area_info["defective_infos"]
                for defective_info in defective_infos:
                    defective_code = defective_info["defective_code"]
                    flaws.append(defective_code)

    try:
        flaws = [str(item) for item in flaws]
        for index, result_item in enumerate(result):
            if index < len(flaws):
                if index == len(result) - 1:
                    result_item["flaw_id"] = ",".join(flaws[index:])
                else:
                    result_item["flaw_id"] = flaws[index]
    except:
        err = traceback.format_exc()
        print(f"-------err: {err}")

    return result, flaws

if __name__ == '__main__':
    result = [{'score': 1.3625821, 'rect': [0.46154514, 0.41203701, 0.8683377, 0.55370367], 'image_path': None}]
    result, flaws = wrapper_flaws(result, "28" , "1")

    print(f"-------result: {result}")
    print(f"-------flaws: {flaws}")